#include <glog/logging.h>
#include <glog/log_severity.h>

#include "client_map.h"

ClientMap* ClientMap::m_pInstance = NULL;

void ClientInfo::operator=(ClientInfo &client)
{
	this->client_ = client.client_;
	this->ice_info_ = client.ice_info_;
	this->type_ = client.type_;
}

int ClientMap::Push(std::string &id, ClientInfo &client)
{
	std::unique_lock<std::mutex> lck(mutex_);

	CLIENT_MAP_ITOR itor = client_map_.find(id);
	if (itor != client_map_.end())
	{
		//LOG(WARNING)<<"ClientMap::Push failed: "<<id<<" already exist";
		return -1;
	}
	else
	{
		client_map_[id] = client;

		if (0 == client.type_)
		{
			id_list_.push_back(id);
		}

		LOG(INFO)<<"ClientMap::Push success: "<<id;
		
		return 0;
	}
}

int ClientMap::Remove(std::string &id)
{
	std::unique_lock<std::mutex> lck(mutex_);

	CLIENT_MAP_ITOR itor = client_map_.find(id);
	if (itor != client_map_.end())
	{
		//client_info cli = itor->second;
		//delete cli.client_;
		
		client_map_.erase(id);
		
		LOG(INFO)<<"ClientMap::Remove success: "<<id;
		
		return 0;
	}
	else
	{
		LOG(ERROR)<<"ClientMap::Remove failed: "<<id;
		
		return -1;
	}
}

int ClientMap::UpdateICE(std::string &id, std::string &ice_info)
{
	std::unique_lock<std::mutex> lck(mutex_);

	CLIENT_MAP_ITOR itor = client_map_.find(id);
	if (itor != client_map_.end())
	{
		ClientInfo *client = &(itor->second);

		client->ice_info_ = ice_info;
		
		LOG(INFO)<<"ClientMap::UpdateICE success, id: "<<id<<" ice: "<<ice_info;
		
		return 0;
	}


	LOG(ERROR)<<"ClientMap::UpdateICE failed, id: "<<id;
	
	return -1;
}

int ClientMap::GetAgent(std::string &id, ClientInfo &client)
{
	std::unique_lock<std::mutex> lck(mutex_);

	CLIENT_MAP_ITOR itor = client_map_.find(id);
	if (itor != client_map_.end())
	{
		LOG(INFO)<<"ClientMap::GetClient success, id: "<<id;

		client = itor->second;
		return 0;
	}

	LOG(ERROR)<<"ClientMap::GetClient failed, id: "<<id;
	
	return -1;
	
}

int ClientMap::GetIDList(ID_LIST &id_list)
{
	std::unique_lock<std::mutex> lck(mutex_);

	ID_LIST_ITOR itor = id_list_.begin();
	for (; itor != id_list_.end(); itor++)
	{
		LOG(INFO)<<"ClientMap::GetIDList, id: "<<*itor;
		id_list.push_back(*itor);
	}

	return 0;
}

ClientMap* ClientMap::Instance()  
{  
	if ( m_pInstance == NULL )
	{
		m_pInstance = new ClientMap();
	}

	return m_pInstance;  
}

